package com.hmall.item.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hmall.common.pojo.PageDTO;
import com.hmall.item.dto.Pageddttoo;
import com.hmall.item.dto.RealmePhone;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ItemService extends ServiceImpl<ItemMapper, Item> implements IItemService {
    @Autowired
    private ItemMapper itemMapper;
    @Override
    public PageDTO PagedQuery(Pageddttoo pageddttoo) {
        PageHelper.startPage(pageddttoo.getPage(), pageddttoo.getSize());
        List<Item> items = itemMapper.selectList(null);
        PageInfo<Item> pageInfo = new PageInfo<>(items);

        PageDTO pageDTO = new PageDTO();
        pageDTO.setTotal(pageInfo.getTotal());
        pageDTO.setList(pageInfo.getList());
        return pageDTO;
    }

    @Override
    public Item selectbyid(Long id) {
        Item item = itemMapper.selectById(id);
        return item;
    }

    @Override
    public void insert(RealmePhone realmePhone) {
        Item bean = BeanUtil.toBean(realmePhone, Item.class);
        itemMapper.insert(bean);
    }

    @Override
    public void update(RealmePhone realmePhone) {
        Item bean = BeanUtil.toBean(realmePhone, Item.class);
        LambdaUpdateWrapper<Item> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Item::getName, realmePhone.getName());
        itemMapper.update(bean,wrapper );
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        Item bean = BeanUtil.toBean(status, Item.class);
        LambdaUpdateWrapper<Item> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(Item::getStatus,status);
        wrapper.eq(Item::getId, id);
        itemMapper.update(bean,wrapper);
    }

    @Override
    public void delete(Long id) {
        LambdaQueryWrapper<Item> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Item::getId, id);
        itemMapper.delete(wrapper);
    }

    @Override
    public void updateStock(Long itemId, Integer num) {
        LambdaUpdateWrapper<Item> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Item::getId, itemId);
        Item item = itemMapper.selectById(itemId);
        Integer stock = item.getStock();
        stock=stock-num;
        wrapper.set(Item::getStock,stock);
        itemMapper.update(null,wrapper);
    }
}
